package com.example.my_dubbo.loadBalance;

import java.util.*;

/**
 * @author 何可人
 * @version 1.0
 * @description: TODO
 * @date 2022/12/9 16:58
 */
public class LeastActiveLoadBalance {
    public static String getServerName(){
        Object[] activities =  ServerIps.ACTIVITY_LIST.values().toArray();
        if(activities==null||activities.length==0){
            return null;
        }
        int minActivity = (int) activities[0];
        for(Object tmp:activities){
            Integer tmpActivity = (Integer) tmp;
            minActivity = Math.min(minActivity, (Integer) tmp);
        }
        List<String> minActivityIps = new ArrayList<>();

        int finalMinActivity = minActivity;
        ServerIps.ACTIVITY_LIST.forEach((ip, activity) -> {
            if (activity == finalMinActivity) {
                minActivityIps.add(ip);
            }
        });

        // 最小活跃数的ip有多个，则根据权重来选，权重大的优先
        if (minActivityIps.size() > 1) {
            // 过滤出对应的ip和权重
            Map<String, Integer> weightList = new LinkedHashMap<String, Integer>();
            ServerIps.WEIGHT_LIST.forEach((ip, weight) -> {
                if (minActivityIps.contains(ip)) {
                    weightList.put(ip, ServerIps.WEIGHT_LIST.get(ip));
                }
            });
            int totalWeight = 0;
            boolean sameWeight = true; // 如果所有权重都相等，那么随机一个ip就好了
            Object[] weights = weightList.values().toArray();
            for (int i = 0; i < weights.length; i++) {
                Integer weight = (Integer) weights[i];
                totalWeight += weight;
                if (sameWeight && i > 0 && !weight.equals(weights[i - 1])) {
                    sameWeight = false;
                }
            }
            Random random = new Random();
            int randomPos = random.nextInt(totalWeight);
            if (!sameWeight) {
                for (String ip : weightList.keySet()) {
                    Integer value = weightList.get(ip);
                    if (randomPos < value) {
                        return ip;
                    }
                    randomPos = randomPos - value;
                }
            }
            return (String) weightList.keySet().toArray()[new Random().nextInt(weightList.size())];
        } else {
            return minActivityIps.get(0);
        }

    }

    public static void main(String[] args) {
        // 连续调用10次,随机10个client
        for (int i = 0; i < 100; i++) {
            System.out.println(getServerName());
        }
    }
}
